package leetcode.other.p977;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

/**
 * 977. 有序数组的平方
 */
class Solution1 {
    public int[] sortedSquares(int[] nums) {
        TreeMap<Integer, Integer> treeMap = new TreeMap<>();
        for (int num : nums) {
            Integer count = treeMap.get(num * num);
            if (count != null) {
                treeMap.put(num * num, count + 1);
            } else {
                treeMap.put(num * num, 1);
            }
        }
        ArrayList<Integer> squareNumList = new ArrayList<>();
        for (Map.Entry<Integer, Integer> numCountEntry : treeMap.entrySet()) {
            for (int i = 0; i < numCountEntry.getValue(); i++) {
                squareNumList.add(numCountEntry.getKey());
            }
        }
        Integer[] squareNums1 = squareNumList.toArray(new Integer[0]);
        int[] squareNums = new int[squareNums1.length];
        for (int i = 0; i < squareNums1.length; i++) {
            squareNums[i] = squareNums1[i];
        }
        return squareNums;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution1().sortedSquares(new int[]{-4,-1,0,3,10})));
        System.out.println(Arrays.toString(new Solution1().sortedSquares(new int[]{-7,-3,2,3,11})));
    }
}